package com.bootdo.clouddo.service.file.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.bootdo.clouddo.service.file.IFileService;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;

@Service
public class FileServiceImpl implements IFileService {
	
	@Value("${qiniu.accessKey}")
	String accessKey;
	
	@Value("${qiniu.secretKey}")
	String secretKey;
	
	@Override
	public String getUpToken(String bucket, long expireSeconds) {
		Auth auth = Auth.create(accessKey, secretKey);
		StringMap putPolicy = new StringMap();
		putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize)}");
		return auth.uploadToken(bucket, null, expireSeconds, putPolicy);
	}

	@Override
	public String getUrl(String key, String domain, long expireSeconds) {
		String encodedFileName = null;
		try {
			encodedFileName = URLEncoder.encode(key, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return String.format("%s/%s", domain, encodedFileName);
	}
	
	@Override
	public FileInfo getFileInfo(String key, String bucket) throws QiniuException{
		Configuration cfg = new Configuration(Zone.zone0());
		Auth auth = Auth.create(accessKey, secretKey);
		BucketManager bucketManager = new BucketManager(auth, cfg);
	    FileInfo fileInfo = bucketManager.stat(bucket, key);
	    return fileInfo;
	}
	
	@Override
	public void move(String fromBucket, String toBucket, String fromKey, String toKey) throws QiniuException{
		Configuration cfg = new Configuration(Zone.zone0());
		Auth auth = Auth.create(accessKey, secretKey);
		BucketManager bucketManager = new BucketManager(auth, cfg);
		bucketManager.move(fromBucket, fromKey, toBucket, toKey);
	}
	
	@Override
	public void copy(String fromBucket, String toBucket, String fromKey, String toKey) throws QiniuException{
		Configuration cfg = new Configuration(Zone.zone0());
		Auth auth = Auth.create(accessKey, secretKey);
		BucketManager bucketManager = new BucketManager(auth, cfg);
		bucketManager.copy(fromBucket, fromKey, toBucket, toKey);
	}
	
	@Override
	public void delete(String key, String bucket) throws QiniuException{
		Configuration cfg = new Configuration(Zone.zone0());
		Auth auth = Auth.create(accessKey, secretKey);
		BucketManager bucketManager = new BucketManager(auth, cfg);
	    bucketManager.delete(bucket, key);
	}
	
	

}
